//
//  AppCommunicationManager.m
//  BanBu
//
//  Created by 来国 郑 on 12-7-26.
//  Copyright (c) 2012年 17xy. All rights reserved.
//


#import "AppCommunicationManager.h"
#import "CJSONSerializer.h"
#import "GTMBase64.h"
#import "NSDictionary_JSONExtensions.h"
#import <CommonCrypto/CommonDigest.h>
#import "AppDataManager.h"
#import "RecordAudio.h"
#import "BanBu_AppDelegate.h"
#import "Reachability.h"
#import "CJSONDeserializer.h"
#import "BanBu_RefreshTime.h"
#import "NSString+SBJSON.h"
#import "LeveyTabBarController.h"
#import "ZipArchive.h"
#import "BanBu_AppDelegate.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_LocationManager.h"
#import "BanBu_LocationManager.h"
#import "PassWord.h"
#import "BanBu_ChatViewController.h"
#import "ASIDownloadCache.h"
#import "NSData+QBase64.h"

#define SERVER_IP @"109.169.66.70"
#define SERVER_PORT 1001
#define GlobleSepTimeInterval  (_netStatus==NetReachableWifi?9:3)
@interface AppCommunicationManager()
{
    
    NSString *isDeep;
    
    MKNetworkEngine *engine;
    
    NSInteger noticeNum;
}




@end

@implementation AppCommunicationManager

@synthesize networkQueue = _networkQueue;
@synthesize chatSocket = _chatSocket;
//what is this
@synthesize receiveSingleMsgTimer=_receiveSingleMsgTimer;
@synthesize delegate=_delegate;
@synthesize receivedata=_receivedata;
@synthesize netStatus=_netStatus;
@synthesize receiveMsgQueue = _receiveMsgQueue;
//修改：yinlinlin
@synthesize updateAlbumdataQueue = _updateAlbumdataQueue;
//修改完成：yinlinlin
static AppCommunicationManager *sharedAppCommunicationManager = nil;

- (void)initRaysource
{
    self.netStatus = ReachableViaWiFi;
    [self creatCachePaths];
    noticeNum = 0;
    _networkQueue = [[ASINetworkQueue alloc] init];
    [_networkQueue setMaxConcurrentOperationCount:2];
    [_networkQueue setShowAccurateProgress:YES];
    [_networkQueue go];
    
    _receiveMsgQueue = [[ASINetworkQueue alloc]init];
    [_receiveMsgQueue setMaxConcurrentOperationCount:2];
    [_receiveMsgQueue setShowAccurateProgress:YES];
    [_receiveMsgQueue go];
    
    _uploadQueue = [[ASINetworkQueue alloc] init];
    [_uploadQueue setMaxConcurrentOperationCount:2];
    [_uploadQueue setShowAccurateProgress:YES];
    [_uploadQueue go];
    
    //修改：yinlinlin：初始化队列
    _updateAlbumdataQueue = [[ASINetworkQueue alloc] init];
    [_updateAlbumdataQueue setMaxConcurrentOperationCount:1];
    [_updateAlbumdataQueue setShowAccurateProgress:YES];
    [_updateAlbumdataQueue go];
    //修改完成：yinlinlin

    _receivedata=[[NSMutableData alloc]init];
    
    _receiveInfo = [[NSMutableDictionary alloc] initWithCapacity:1];
    
    // 写一个MKNETENG
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    self.hostReach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    [_hostReach startNotifier];
}

- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    
    //有的方法的条件可以满足可以不满足，都不影响执行。但如果你希望程序在某些条件不满足的时候产生错误告诉你，就用nsparameterassert让程序崩溃。
    
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    NetworkStatus status = [curReach currentReachabilityStatus];
    AppLocationManager.netStatus = status;
    // 判断是不是3G Wifi 还是没有网络
    _netStatus=(int)status;
    [[NSNotificationCenter defaultCenter] postNotificationName:NetWork_Unable object:[NSNumber numberWithInt:_netStatus]];

    if (status ==  NotReachable && !isReach)
    {
        isReach = YES;
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"network_unavailabel", nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"confirmNotice", nil) otherButtonTitles: nil];
        [alertView show];
        [alertView release];
        if(_receiveMsgTimer)
        {
            [_receiveMsgTimer invalidate];
            
            _receiveMsgTimer = nil;
        }
    }
    else
    {
//        NSInteger total = 0;
//        for(NSDictionary *aTalk in MyAppDataManager.talkPeoples)
//        {
//            total += [VALUE(KeyUnreadNum, aTalk) integerValue];
//        }
//        
//        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",total],@"pushcount",nil];
//        [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:dic delegate:self];
        
        isReach = NO;
        // 判断网络是WIFI 还是3g
        if([_receiveInfo count])
        {
            if(_receiveMsgTimer)
            {
                [_receiveMsgTimer invalidate];
                _receiveMsgTimer = nil;
            }
            _receiveMsgTimer = [NSTimer scheduledTimerWithTimeInterval:SepTimeInterval
                                                                target:self
                                                              selector:@selector(receviceMsg)
                                                              userInfo:nil
                                                               repeats:YES];
            
            [[NSRunLoop currentRunLoop] addTimer:_receiveMsgTimer forMode:NSDefaultRunLoopMode];
        }
    }
}

- (void)creatCachePaths
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"];
    NSArray *cachePaths = [NSArray arrayWithObjects:[cachePath stringByAppendingPathComponent:@"ChatImage"],[cachePath stringByAppendingPathComponent:@"ChatAudio"],nil];
    
    for(NSString *path in cachePaths)
    {
        if (![[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:path
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
    }
}

+ (AppCommunicationManager *)sharedAppCommunicationManager;
{
    @synchronized(self){
        if(sharedAppCommunicationManager == nil){
            sharedAppCommunicationManager = [[[self alloc] init] autorelease];
            [sharedAppCommunicationManager initRaysource];
        }
    }
    return sharedAppCommunicationManager;
}

+(id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (sharedAppCommunicationManager == nil) {
            sharedAppCommunicationManager = [super allocWithZone:zone];
            return  sharedAppCommunicationManager;
        }
    }
    return nil;
}

- (NSString *)getPar:(NSString *)parStr
{
    NSInteger start = [parStr rangeOfString:@"/" options:NSBackwardsSearch].location+2;
    NSInteger end = [parStr rangeOfString:@".php?" options:NSBackwardsSearch].location;
    return [parStr substringWithRange:NSMakeRange(start, end-start)];
    
}

- (BOOL)respondsDic:(NSDictionary *)dataDic isFunctionData:(NSString *)fc
{
    NSString *fcKey = [self getPar:fc];
    
    return [[dataDic valueForKey:@"fc"] isEqualToString:fcKey];
}

#pragma mark - 公共方法：取消代理
- (void)cancalHandlesForObject:(id)adelegate
{
    for(ASIHTTPRequest *request in _networkQueue.operations)
    {
        if(request.delegate == adelegate)
        {
            [request clearDelegatesAndCancel];
        }
    }
}

- (void)cancalHandleNemed:(NSString *)name forObject:(id)adelegate
{
    for(ASIHTTPRequest *request in _networkQueue.operations)
    {
        if(request.delegate == adelegate && [request.username isEqualToString:name])
        {
            [request clearDelegatesAndCancel];
        }
    }
}
/**
 *	@brief	获取地理位置信息
 *
 *	@param 	_loc 	坐标
 *	@param 	adelegate 	delegate
 */
- (void)getBanBuPosition:(CLLocation *)_loc delegate:(id)adelegate
{
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?latlng=%.2f,%.2f&sensor=true",[_loc coordinate].latitude,[_loc coordinate].longitude];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    urlString = [NSString stringWithFormat:@"%@&language=%@",urlString,[MyAppDataManager getLanguageSubmitToGoogle]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.delegate = adelegate;
    [request setRequestMethod:@"Get"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            [respondsDic setValue:@"get_location" forKey:@"fc"];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [respondsDic setValue:[NSNumber numberWithBool:NO] forKey:@"ok"];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom = [resStr dataUsingEncoding:NSUTF8StringEncoding];
            [respondsDic setValue:[NSJSONSerialization JSONObjectWithData:resFrom options:NSJSONReadingMutableLeaves error:&error] forKey:@"result"];
            
            [respondsDic setValue:[NSNumber numberWithBool:YES] forKey:@"ok"];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            
        }
        
    }];
    [_networkQueue addOperation:request];
}


#pragma mark - 公共方法：获取服务器数据
//已登录的用户
- (void)getBanBuData:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr;
    //如果是获取服务器列表
    if ([query isEqualToString:BanBu_Get_Server_List])
    {
        requestUrlStr = [BanBuHost stringByAppendingString:query];
    }
    else
    {
        requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    }
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];

    
    if ([query isEqualToString:BanBu_SendMessage_To_Server_V2])
    {
        NSDictionary *says = [parDic valueForKey:@"says"];
        NSString *jsonValue = [[CJSONSerializer serializer] serializeDictionary:says];
        jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        [pars setValue:jsonValue forKey:@"says"];
    }
    if([query isEqualToString:BanBu_Send_Broadcast] ||[query isEqualToString:BanBu_Reply_Broadcast]){
        NSDictionary *says = [parDic objectForKey:@"says"];
//        NSLog(@"%@",says);
        NSString *jsonValue = [[CJSONSerializer serializer] serializeDictionary:says];
        jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        [pars setValue:jsonValue forKey:@"says"];
    }
    [pars setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
    [pars setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    //2014年11月19日15:58:45 by yinlinlin 注册接口不添加loginid
    if ([query isEqualToString:BanBu_Set_Register_User_Onekey])
    {
        [pars removeObjectForKey:@"loginid"];
    }
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSLog(@"提交参数%@",pars);
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    NSLog(@"jsonfrom:%@",jsonfrom);
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];

    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        
        if(([query isEqualToString:BanBu_Check_Login]||[query isEqualToString:BanBu_Set_Register_User]))
        {
            if(noticeNum<3)
            {
                double delayInSeconds = 5.0;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self getBanBuData:query par:parDic delegate:adelegate];
                });
                noticeNum++;
                return;
            }
            else
            {
                noticeNum = 0;
            }
        }
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:parDic];
            
            if ([query isEqualToString:BanBu_SendMessage_To_Server_V2])
            {
                [respondsDic addEntriesFromDictionary:parDic];
                [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
                [respondsDic setValue:[NSNumber numberWithInteger:ChatStatusSendFail] forKey:KeyStatus];
                [respondsDic setValue:[parDic valueForKey:@"touid_list"] forKey:KeyUid];
            }
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([query isEqualToString:BanBu_Check_Login]||[query isEqualToString:BanBu_Register_Email])
        {
            noticeNum = 0;
        }
        if([query isEqualToString:BanBu_Check_Login])
        {
            NSLog(@"LoginReturn : %@",[request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]);
        }
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            if ([query isEqualToString:BanBu_SendMessage_To_Server_V2])
            {
                [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
                [respondsDic setValue:[parDic valueForKey:@"touid_list"] forKey:KeyUid];
            }
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            if ([query isEqualToString:BanBu_GetMagicGid_detail])
            {
                [respondsDic setValue:[parDic valueForKey:@"title"] forKey:@"title"];
            }
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                // 国际化语言包
                if([query isEqualToString:BanBu_Get_Friend_FriendDo] || [query isEqualToString:BanBu_Get_Friend_FriendDos] || [query isEqualToString:BanBu_Get_User_Neardo]|| [query isEqualToString:BanBu_Get_Broadcast] ||[query isEqualToString:BanBu_Get_Broadmaster_byid])
                {
                    if([MyAppDataManager.languageDictionary allValues].count == 0)
                    {
                        NSString *langugagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"InterNationalanguage"];
                        [MyAppDataManager.languageDictionary removeAllObjects];
                        [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:langugagePath]]];
                    }
                    NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                    
                    string =[MyAppDataManager  IsInternationalLanguage:string];
                    
                    resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                    
                    [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                }
                
                if([respondsDic valueForKey:@"alert"])
                {
                    UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:[respondsDic valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                    [alert release];
                }
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    [request startAsynchronous];
//    [_networkQueue addOperation:request];
}

//未登录的用户
-(void)getBanBuData:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate Unlogin:(BOOL)flag
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            [respondsDic setValue:[parDic valueForKey:@"touid"] forKey:KeyUid];
            [respondsDic setValue:query forKey:@"fc"];
            [respondsDic setValue:[parDic valueForKey:@"msgid"] forKey:@"requestid"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            [respondsDic setValue:[parDic valueForKey:@"touid"] forKey:KeyUid];
            [respondsDic setValue:query forKey:@"fc"];
            [respondsDic setValue:[parDic valueForKey:@"msgid"] forKey:@"requestid"];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                
                
            }else{
                // 国际化语言包
                
                
                
                if([MyAppDataManager.languageDictionary allValues].count == 0){
                    NSString *langugagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"InterNationalanguage"];
                    [MyAppDataManager.languageDictionary removeAllObjects];
                    [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:langugagePath]]];
                }
                //                NSLog(@"%@",MyAppDataManager.languageDictionary);
                NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                
                string =[MyAppDataManager  IsInternationalLanguage:string];
                
                resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                
                [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    
    [_networkQueue addOperation:request];
    
}

//获取服务器上多媒体数据：图片、语音等
- (void)getBanBuMedia:(NSString *)mediaUrlStr delegate:(id)adelegate
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [self pathForMedia:mediaUrlStr];

    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    
    request.delegate = adelegate;
    request.username = @"playvoice";
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([adelegate respondsToSelector:@selector(removeTk)])
        {
            [adelegate removeTk];
            
        }else if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:@"n" forKey:@"ok"];
            
            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    
    [request setCompletionBlock:^{
        
        if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            if([[mediaUrlStr pathExtension] isEqualToString:@"amr"])
            {
                NSData *audioData = [RecordAudio decodeAMRToWav:savePath];
                [FileManager createFileAtPath:savePath contents:audioData attributes:nil];
            }
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:mediaUrlStr forKey:@"oldImageUrl"];
            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    
    [_networkQueue addOperation:request];
    
}

//获取服务器上对话部分多媒体信息：图片、语音等
- (void)getBanBuMedia:(NSString *)mediaUrlStr forMsgID:(NSString *)msgid fromUid:(NSString *)uid delegate:(id)adelegate
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [self pathForMsgMedia:mediaUrlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    request.delegate = adelegate;
    request.username = [NSString stringWithFormat:@"%@-%@",msgid,mediaUrlStr];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:downloadDataProgress:)])
         {
             NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
             [respondsDic setValue:uid forKey:KeyUid];
             [respondsDic setValue:msgid forKey:KeyChatid];
             
             [blockDelegate banbuRequestNamed:respondsDic downloadDataProgress:(float)(request.totalBytesRead-request.totalBytesSent)/(total-request.totalBytesSent)];
         }
         
     }];
    
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        float time=0.f;
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            if([[mediaUrlStr pathExtension] isEqualToString:@"amr"])
            {
                NSData *audioData = [RecordAudio decodeAMRToWav:savePath];
                if(audioData){
                    [FileManager createFileAtPath:savePath contents:audioData attributes:nil];
                    
                    RecordAudio *recod=[[[RecordAudio alloc]init] autorelease];
                    
                    time = [recod playDuration:audioData];
                    
                }
            }
            else if([[mediaUrlStr pathExtension] isEqualToString:@"mp4"])
            {
                [FileManager moveItemAtPath:[AppComManager pathForMsgMedia:mediaUrlStr] toPath:[NSString stringWithFormat:@"%@.mp4",[AppComManager pathForVideoMsgMedia:mediaUrlStr]] error:nil];
            }
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [respondsDic setValue:@"y" forKey:@"ok"];
            
            [respondsDic setValue:[NSNumber numberWithFloat:time ] forKey:@"time"];
            
            [respondsDic setValue:mediaUrlStr forKey:@"mediaUrlStr"];
            
            
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    [_networkQueue addOperation:request];
}

//获取视频的缩略图
- (void)getBanBuMediaThumbnail:(NSString *)mediaUrlStr forMsgID:(NSString *)msgid fromUid:(NSString *)uid delegate:(id)adelegate
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [NSString stringWithFormat:@"%@.jpg",[self pathForVideoMsgMedia:mediaUrlStr]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    request.delegate = adelegate;
    request.username = [NSString stringWithFormat:@"%@-%@",msgid,mediaUrlStr];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:downloadDataProgress:)])
         {
             NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
             [respondsDic setValue:uid forKey:KeyUid];
             [respondsDic setValue:msgid forKey:KeyChatid];
             
             [blockDelegate banbuRequestNamed:respondsDic downloadDataProgress:(float)(request.totalBytesRead-request.totalBytesSent)/(total-request.totalBytesSent)];
         }
         
     }];
    
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:@"thumbnail" forKey:@"thumbnail"];
            
            [respondsDic setValue:mediaUrlStr forKey:@"mediaUrlStr"];
            
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    [_networkQueue addOperation:request];
}


//获取服务器上对话部分多媒体信息：魔法表情等
- (void)getBanBuMagicGifMedia:(NSString *)mediaUrlStr forMsgID:(NSString *)msgid fromUid:(NSString *)uid delegate:(id)adelegate
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [self pathForMsgMedia:mediaUrlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    request.delegate = adelegate;
    request.username = [NSString stringWithFormat:@"%@-%@",msgid,mediaUrlStr];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:downloadDataProgress:)])
         {
             NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
             [respondsDic setValue:uid forKey:KeyUid];
             [respondsDic setValue:msgid forKey:KeyChatid];
             
             [blockDelegate banbuRequestNamed:respondsDic downloadDataProgress:(float)(request.totalBytesRead-request.totalBytesSent)/(total-request.totalBytesSent)];
         }
         
     }];
    
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:mediaUrlStr forKey:@"mediaUrlStr"];
            [respondsDic setValue:@"magicFace" forKey:@"type"];//当有该字段时，说明下载的是魔法表情，不需要重设cell的高度
            
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    [_networkQueue addOperation:request];
}

//获取魔法表情的缩略图
- (void)getBanBuMediaMagicThumbnail:(NSString *)mediaUrlStr forMsgID:(NSString *)msgid fromUid:(NSString *)uid delegate:(id)adelegate
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [NSString stringWithFormat:@"%@",[self pathForMsgMedia:mediaUrlStr]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    request.delegate = adelegate;
    request.username = [NSString stringWithFormat:@"%@-%@",msgid,mediaUrlStr];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:downloadDataProgress:)])
         {
             NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
             [respondsDic setValue:uid forKey:KeyUid];
             [respondsDic setValue:msgid forKey:KeyChatid];
             
             [blockDelegate banbuRequestNamed:respondsDic downloadDataProgress:(float)(request.totalBytesRead-request.totalBytesSent)/(total-request.totalBytesSent)];
         }
         
     }];
    
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:uid forKey:KeyUid];
            [respondsDic setValue:msgid forKey:KeyChatid];
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:@"thumbnail" forKey:@"thumbnail"];
            
            [respondsDic setValue:mediaUrlStr forKey:@"mediaUrlStr"];
            
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    [_networkQueue addOperation:request];
}

-(void)getTranslateUrl:(NSString *)urlString delegate:(id)adelegate
{
    //去空格
    urlString = [self trimBlankString:urlString];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:5];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            resStr = [[resStr dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [_networkQueue addOperation:request];
    
}

//获取服务器上多媒体数据：图片、语音等
- (void)getBanBuMagicHtml:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    NSMutableDictionary *pars = [[NSMutableDictionary alloc]initWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:parDic];
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                
                string =[MyAppDataManager  IsInternationalLanguage:string];
                
                resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                
                [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                
                if([respondsDic valueForKey:@"alert"])
                {
                    UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:[respondsDic valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                    [alert release];
                }
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];

    
    [_networkQueue addOperation:request];
    
}

#pragma mark - 提交收藏的表情、图片、文字、语音

//提交服务器收藏的表情,下载收藏的表情
- (void)getBanBuDataWIthCollectEmo:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    
    NSMutableDictionary *pars = [[NSMutableDictionary alloc]initWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"收藏上传参数：%@",pars);
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:parDic];
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                // 国际化语言包
                if([query isEqualToString:BanBu_Get_Friend_FriendDo] || [query isEqualToString:BanBu_Get_Friend_FriendDos] || [query isEqualToString:BanBu_Get_User_Neardo]|| [query isEqualToString:BanBu_Get_Broadcast] ||[query isEqualToString:BanBu_Get_Broadmaster_byid])
                {
                    if([MyAppDataManager.languageDictionary allValues].count == 0)
                    {
                        NSString *langugagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"InterNationalanguage"];
                        [MyAppDataManager.languageDictionary removeAllObjects];
                        [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:langugagePath]]];
                    }
                    NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                    
                    string =[MyAppDataManager  IsInternationalLanguage:string];
                    
                    resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                    
                    [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                }
                
                if([respondsDic valueForKey:@"alert"])
                {
                    UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:[respondsDic valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                    [alert release];
                }
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [_networkQueue addOperation:request];
}

//提交服务器收藏的文本、图片、语音
- (void)uploadCollectManuscript:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    
    NSMutableDictionary *pars = [[NSMutableDictionary alloc]initWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        
        if(([query isEqualToString:BanBu_Check_Login]||[query isEqualToString:BanBu_Set_Register_User]))
        {
            if(noticeNum<3)
            {
                double delayInSeconds = 5.0;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self getBanBuData:query par:parDic delegate:adelegate];
                });
                noticeNum++;
                return;
            }
            else
            {
                noticeNum = 0;
            }
        }
        
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:parDic];
            
            if ([query isEqualToString:BanBu_SendMessage_To_Server_V2])
            {
                [respondsDic addEntriesFromDictionary:parDic];
                [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
                [respondsDic setValue:[NSNumber numberWithInteger:ChatStatusSendFail] forKey:KeyStatus];
                [respondsDic setValue:[parDic valueForKey:@"touid_list"] forKey:KeyUid];
            }
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([query isEqualToString:BanBu_Check_Login]||[query isEqualToString:BanBu_Register_Email])
        {
            noticeNum = 0;
        }
        if([query isEqualToString:BanBu_Check_Login])
        {
            NSLog(@"LoginReturn : %@",[request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]);
        }
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            if ([query isEqualToString:BanBu_SendMessage_To_Server_V2])
            {
                [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
                [respondsDic setValue:[parDic valueForKey:@"touid_list"] forKey:KeyUid];
            }
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            if ([query isEqualToString:BanBu_GetMagicGid_detail])
            {
                [respondsDic setValue:[parDic valueForKey:@"title"] forKey:@"title"];
            }
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                // 国际化语言包
                if([query isEqualToString:BanBu_Get_Friend_FriendDo] || [query isEqualToString:BanBu_Get_Friend_FriendDos] || [query isEqualToString:BanBu_Get_User_Neardo]|| [query isEqualToString:BanBu_Get_Broadcast] ||[query isEqualToString:BanBu_Get_Broadmaster_byid])
                {
                    if([MyAppDataManager.languageDictionary allValues].count == 0)
                    {
                        NSString *langugagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"InterNationalanguage"];
                        [MyAppDataManager.languageDictionary removeAllObjects];
                        [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:langugagePath]]];
                    }
                    NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                    
                    string =[MyAppDataManager  IsInternationalLanguage:string];
                    
                    resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                    
                    [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                }
                
                if([respondsDic valueForKey:@"alert"])
                {
                    UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:[respondsDic valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                    [alert release];
                }
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [_networkQueue addOperation:request];
}

#pragma mark - 获取魔法文字的html
-(void)getMagicWordsHtml:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    //去空格
    
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    NSMutableDictionary *pars = [[NSMutableDictionary alloc]initWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:5];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [_networkQueue addOperation:request];
    
}

#pragma mark - 公共方法：文件上传
- (void)uploadRegAvatarImage:(NSData *)imageData Par:(NSDictionary *)parDic delegate:(id)adelegate;
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Set_User_Avatar];    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_Set_User_Avatar] forKey:@"fc"];
    //    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSString *encodedStr = [imageData base64EncodedString];
    [pars setValue:encodedStr forKey:@"photofile"];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    
    [request setPostValue:jsonfrom forKey:@"jsonfrom"];
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    
    [request setFailedBlock:^{
        if(noticeNum<3)
        {
            double delayInSeconds = 5.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self uploadRegAvatarImage:imageData Par:parDic delegate:adelegate];
            });
            noticeNum ++;
            return ;
        }
        else
        {
            noticeNum = 0;
        }
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            [blockDelegate banbuRequestDidFinished:[NSDictionary dictionaryWithObjectsAndKeys:[self getPar:BanBu_Set_User_Avatar],@"fc",nil] error:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        noticeNum = 0;
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            NSDictionary *respondsDic = [NSDictionary dictionaryWithJSONData:resFrom64 error:&error];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    
    [_networkQueue addOperation:request];
    
}
- (void)uploadOneImages:(NSArray *)imageArr delegate:(id)delegate{
    
}


- (void)uploadSeveralImages:(NSArray *)imageArr delegate:(id)delegate
{
    ASINetworkQueue *uploadQueue = [[ASINetworkQueue alloc] init];
    uploadQueue.delegate = self;
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:delegate forKey:@"adelegate"];
    uploadQueue.userInfo = userInfo;
    [uploadQueue setQueueDidFinishSelector:@selector(uploadFinished:)];
    [uploadQueue setMaxConcurrentOperationCount:2];
    [uploadQueue setShowAccurateProgress:YES];
    [uploadQueue go];
    
    for(int i=0; i<imageArr.count; i++)
    {
        UIImage *image = [imageArr objectAtIndex:i];
        NSString *imagePathExtension = @"jpg";
        NSData *imageData ;
        
        imageData = UIImageJPEGRepresentation(image, 0.7);
          
        NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Set_User_Avatar];
        
        NSMutableDictionary *pars = [NSMutableDictionary dictionary];
        [pars setValue:@"y" forKey:@"phone"];
        [pars setValue:imagePathExtension forKey:@"picformat"];
        [pars setValue:[self getPar:BanBu_Set_User_Avatar] forKey:@"fc"];
        [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
        NSString *encodedStr = [imageData base64EncodedString];
        [pars setValue:encodedStr forKey:@"photofile"];
        
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
        jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        //去空格
        requestUrlStr = [self trimBlankString:requestUrlStr];
        
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
        [request setPostValue:jsonfrom forKey:@"jsonfrom"];
        
        [request setFailedBlock:^{
//            if (noticeNum<3) {
//                MyAppDataManager.banbuHostIP = BanBuHost;
//                [MyAppDelegate getServerList];
//                noticeNum ++;
//            }
            NSLog(@"上传照片失败了一张");
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:uploadQueue.userInfo];
            NSInteger failNum = [[userInfo valueForKey:@"failNum"] integerValue];
            failNum ++;
            [userInfo setValue:[NSNumber numberWithInteger:failNum] forKey:@"failNum"];
            uploadQueue.userInfo = userInfo;
            
        }];
        [request setCompletionBlock:^{
            NSLog(@"上传照片成功了一张");
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:uploadQueue.userInfo];
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            if(resStr.length)
            {
                NSData *resFrom64 = [NSData dataFromBase64String:resStr];
                
                NSDictionary *respondsDic = [NSDictionary dictionaryWithJSONData:resFrom64 error:nil];
                
                if([[respondsDic valueForKey:@"ok"] boolValue])
                {
                    NSInteger successNum = [[userInfo valueForKey:@"c"] integerValue];
                    successNum ++;
                    [userInfo setValue:[NSNumber numberWithInteger:successNum] forKey:@"successNum"];
                    [userInfo setValue:[respondsDic valueForKey:@"facelist"] forKey:@"facelist"];
                    uploadQueue.userInfo = userInfo;
                    return;
                }
            }
            NSInteger failNum = [[userInfo valueForKey:@"failNum"] integerValue];
            failNum ++;
            [userInfo setValue:[NSNumber numberWithInteger:failNum] forKey:@"failNum"];
            uploadQueue.userInfo = userInfo;
            
        }];
        [uploadQueue addOperation:request];
    }
}

- (void)uploadBanBuMedia:(NSData *)mediaData mediaName:(NSString *)mediaName par:(NSDictionary *)parDic delegate:(id)adelegate
{
    RecordAudio *recod=[[RecordAudio alloc]init];
    
    float time = [recod playDuration:mediaData];
    [recod release];
    
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_File_Bychat];
    
     NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_Post_File_Bychat] forKey:@"fc"];
//    NSString *encodedStr = [mediaData base64EncodedString];
//    [pars setValue:encodedStr forKey:@"sfile"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    [pars setValue:@"chat" forKey:@"filefor"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setRequestMethod:@"POST"];
    request.uploadProgressDelegate = nil;
    
    [request addPostValue:jsonfrom forKey:@"jsonfrom"];
    
//    [request addPostValue:mediaData forKey:@"sfile"];
    //2014年11月06日17:24:13 by yinlinlin 修改使用post上传文件
    NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
    
    if ([[mediaName pathExtension] isEqualToString:@"amr"]||[[mediaName pathExtension] isEqualToString:@"wav"])
    {
        media = @"audio";
    }
    else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
    {
        media = @"image";
    }
    else if([[mediaName pathExtension]isEqualToString:@"mp4"])
    {
        media = @"video";
    }
    
    NSString * contentType = [NSString stringWithFormat:@"%@/%@",media,[mediaName pathExtension]];
    [request addData:mediaData withFileName:media andContentType:contentType forKey:@"sfile"];

    request.delegate = self;
    request.username = mediaName;
    NSLog(@"上传数据：%llu",request.totalBytesSent);
    __block typeof(adelegate)blockDelegate = adelegate;
    NSString *chatUid = [parDic valueForKey:KeyUid];
    [request setUploadSizeIncrementedBlock:^(long long size) {
        request.totalBytesRead = request.totalBytesSent;
        NSLog(@"上传数据：%llu",request.totalBytesSent);
    }];
    
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total)
     {
         //         [MyAppDataManager showNowTime:@"开始上传1"];
         
         NSLog(@"上传数据：%llu %llu %llu",request.totalBytesSent,size,total);

         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:uploadDataProgress:)])
         {
             //             [blockDelegate banbuRequestNamed:request.username uploadDataProgress:(float)(request.totalBytesSent)/(total)];
         }
         
     }];
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            NSError *error = nil;
            NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
            
            if ([[mediaName pathExtension] isEqualToString:@"amr"] || [[mediaName pathExtension] isEqualToString:@"wav"])
            {
                media = @"sound";
            }
            else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
            {
                media = @"image";
            }
            else if([[mediaName pathExtension]isEqualToString:@"mp4"])
            {
                media = @"video";
            }
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:[parDic valueForKey:KeyShowFrom] forKey:KeyShowFrom];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
                
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            [respondsDic setValue:media forKey:@"mediatype"];
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if(![[respondsDic valueForKey:@"ok"] boolValue])
            {
                return;
            }
            
            [respondsDic setValue:@"mo" forKey:KeyShowFrom];
            if ([[mediaName pathExtension]isEqualToString:@"mp4"])
            {
                NSString *oldAudioPath = [self pathForVideoMsgMedia:[parDic valueForKey:KeyContent]];
                NSString *newVideoPath = [self pathForVideoMsgMedia:[respondsDic valueForKey:@"fileurl"]];
                
                [FileManager moveItemAtPath:[NSString stringWithFormat:@"%@.mp4",oldAudioPath] toPath:[NSString stringWithFormat:@"%@.mp4",newVideoPath] error:nil];
            }
            else
            {
                NSString *oldAudioPath = [self pathForMsgMedia:mediaName];
                [FileManager moveItemAtPath:oldAudioPath toPath:[self pathForMsgMedia:[respondsDic valueForKey:@"fileurl"]] error:nil];
            }
            // 将时间传过去
            [respondsDic setValue:[NSNumber numberWithFloat:time] forKey:@"time"];
            
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
        }
    }];
    
    [_networkQueue addOperation:request];
}

- (void)uploadBanBuMediaThumbnail:(NSData *)mediaData mediaName:(NSString *)mediaName par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_File_Bychat];
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_Post_File_Bychat] forKey:@"fc"];

//    NSString *encodedStr = [mediaData base64EncodedString];
//    [pars setValue:mediaData forKey:@"sfile"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    [pars setValue:@"chat" forKey:@"filefor"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setRequestMethod:@"POST"];
    request.uploadProgressDelegate = nil;
    [request setUploadProgressDelegate:nil];
    
    [request addPostValue:jsonfrom forKey:@"jsonfrom"];
//    [request addPostValue:mediaData forKey:@"sfile"];
    
    //2014年11月06日17:24:13 by yinlinlin 修改使用post上传文件
    NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
    
    if ([[mediaName pathExtension] isEqualToString:@"amr"]||[[mediaName pathExtension] isEqualToString:@"wav"])
    {
        media = @"audio";
    }
    else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
    {
        media = @"image";
    }
    else if([[mediaName pathExtension]isEqualToString:@"mp4"])
    {
        media = @"video";
    }
    
    NSString * contentType = [NSString stringWithFormat:@"%@/%@",media,[mediaName pathExtension]];
    [request addData:mediaData withFileName:media andContentType:contentType forKey:@"sfile"];
    
    request.delegate = self;
    request.username = mediaName;
    
    __block typeof(adelegate)blockDelegate = adelegate;
    NSString *chatUid = [parDic valueForKey:KeyUid];
    [request setUploadSizeIncrementedBlock:^(long long size) {
        request.totalBytesRead = request.totalBytesSent;
    }];
    
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total)
     {
     }];
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            NSError *error = nil;
            NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
            
            if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
            {
                media = @"image";
            }
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:[parDic valueForKey:KeyShowFrom] forKey:KeyShowFrom];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            [respondsDic setValue:@"thumbnail" forKey:@"thumbnail"];//上传的是缩略图时有值，其他无值；
            
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
                
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            [respondsDic setValue:media forKey:@"mediatype"];
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if(![[respondsDic valueForKey:@"ok"] boolValue])
            {
                return;
            }
            
            [respondsDic setValue:@"mo" forKey:KeyShowFrom];
            
            NSString *oldAudioPath = [NSString stringWithFormat:@"%@.jpg",[self pathForVideoMsgMedia:[parDic valueForKey:KeyContent]]];
            NSString *newThumbnailPath = [NSString stringWithFormat:@"%@.jpg",[self pathForVideoMsgMedia:[respondsDic valueForKey:@"fileurl"]]];
            
//            NSLog(@"缩略图：oldThumbnailPath：%@,content:%@;newThumbnailPath：%@,content:%@",oldAudioPath,[parDic valueForKey:KeyContent],newThumbnailPath,[respondsDic valueForKey:@"fileurl"]);
            
            [FileManager moveItemAtPath:oldAudioPath toPath:newThumbnailPath error:nil];
            
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
        }
    }];
    
    [_networkQueue addOperation:request];
}

- (void)uploadBanBuBroadcastMedia:(NSData *)mediaData mediaName:(NSString *)mediaName par:(NSDictionary *)parDic delegate:(id)adelegate{
    
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_File_Bybroad];
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_Post_File_Bybroad] forKey:@"fc"];

//    NSString *encodedStr = [mediaData base64EncodedString];
//    [pars setValue:encodedStr forKey:@"sfile"];
    [pars setValue:@"action" forKey:@"filefor"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setRequestMethod:@"POST"];
    [request setShowAccurateProgress:YES];
    [request addPostValue:jsonfrom forKey:@"jsonfrom"];
    
    //2014年11月06日17:24:13 by yinlinlin 修改使用post上传文件
    NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
    
    if ([[mediaName pathExtension] isEqualToString:@"amr"]||[[mediaName pathExtension] isEqualToString:@"wav"])
    {
        media = @"audio";
    }
    else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
    {
        media = @"image";
    }
    else if([[mediaName pathExtension]isEqualToString:@"mp4"])
    {
        media = @"video";
    }
    
    NSString * contentType = [NSString stringWithFormat:@"%@/%@",media,[mediaName pathExtension]];
    [request addData:mediaData withFileName:media andContentType:contentType forKey:@"sfile"];
    
    request.delegate = self;
    request.username = mediaName;
    
    __block typeof(adelegate)blockDelegate = adelegate;
    
    
    [request setFailedBlock:^{
//        if (noticeNum<3) {
//            MyAppDataManager.banbuHostIP = BanBuHost;
//            [MyAppDelegate getServerList];
//            noticeNum ++;
//        }
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            NSError *error = nil;
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
                
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
        }
    }];
    
    [_networkQueue addOperation:request];
}

//上传收藏的表情
- (void)uploadCollectedEmo1:(NSData *)mediaData mediaName:(NSString *)mediaName par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_File_Bychat];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_Post_File_Bychat] forKey:@"fc"];
//    NSString *encodedStr = [mediaData base64EncodedString];
//    [pars setValue:mediaData forKey:@"sfile"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    [pars setValue:@"chat" forKey:@"filefor"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setRequestMethod:@"POST"];
    request.uploadProgressDelegate = nil;
    
    [request addPostValue:jsonfrom forKey:@"jsonfrom"];
//    [request addPostValue:mediaData forKey:@"sfile"];
    
    //2014年11月06日17:24:13 by yinlinlin 修改使用post上传文件
    NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
    
    if ([[mediaName pathExtension] isEqualToString:@"amr"]||[[mediaName pathExtension] isEqualToString:@"wav"])
    {
        media = @"audio";
    }
    else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
    {
        media = @"image";
    }
    else if([[mediaName pathExtension]isEqualToString:@"mp4"])
    {
        media = @"video";
    }
    
    NSString * contentType = [NSString stringWithFormat:@"%@/%@",media,[mediaName pathExtension]];
    [request addData:mediaData withFileName:media andContentType:contentType forKey:@"sfile"];    request.delegate = self;
    request.userInfo = parDic;
    
    __block typeof(adelegate)blockDelegate = adelegate;
    NSString *chatUid = [parDic valueForKey:KeyUid];
    [request setUploadSizeIncrementedBlock:^(long long size) {
        request.totalBytesRead = request.totalBytesSent;
    }];
    
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total)
     {
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:uploadDataProgress:)])
         {
         }
         
     }];
    
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.userInfo forKey:@"requestname"];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            NSError *error = nil;
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:request.userInfo];
            
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
                
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if(![[respondsDic valueForKey:@"ok"] boolValue])
            {
                return;
            }
            
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
        }
    }];
    
    [_networkQueue addOperation:request];
}

//上传收藏的表情
- (void)uploadCollectedEmo:(NSData *)mediaData mediaName:(NSString *)mediaName par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_AddFavFile_ByPost];
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[self getPar:BanBu_AddFavFile_ByPost] forKey:@"fc"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    [pars setValue:@"chat" forKey:@"filefor"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setRequestMethod:@"POST"];
    request.uploadProgressDelegate = nil;
    
    NSString *media = [[mediaName pathExtension] isEqualToString:@"amr"]?@"sound":@"image";
    
    if ([[mediaName pathExtension] isEqualToString:@"amr"]||[[mediaName pathExtension] isEqualToString:@"wav"])
    {
        media = @"audio";
    }
    else if([[mediaName pathExtension] isEqualToString:@"jpg"] || [[mediaName pathExtension] isEqualToString:@"png"])
    {
        media = @"image";
    }
    else if([[mediaName pathExtension]isEqualToString:@"mp4"])
    {
        media = @"video";
    }
    
    NSString * contentType = [NSString stringWithFormat:@"%@/%@",media,[mediaName pathExtension]];
    
    [request addData:mediaData withFileName:mediaName andContentType:contentType forKey:@"sfile"];
    [request addPostValue:jsonfrom forKey:@"jsonfrom"];
    
    request.delegate = self;
    request.userInfo = parDic;
    
    __block typeof(adelegate)blockDelegate = adelegate;
    NSString *chatUid = [parDic valueForKey:KeyUid];
    [request setUploadSizeIncrementedBlock:^(long long size) {
        request.totalBytesRead = request.totalBytesSent;
    }];
    
    [request setBytesSentBlock:^(unsigned long long size, unsigned long long total)
     {
         if([blockDelegate respondsToSelector:@selector(banbuRequestNamed:uploadDataProgress:)])
         {
         }
         
     }];
    
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.userInfo forKey:@"requestname"];
            [respondsDic setValue:chatUid forKey:KeyUid];
            [respondsDic setValue:[parDic valueForKey:KeyChatid] forKey:KeyChatid];
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuUploadRequest:didFinishedWithError:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            NSError *error = nil;
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:request.userInfo];
            
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
                
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if(![[respondsDic valueForKey:@"ok"] boolValue])
            {
                return;
            }
            
            [blockDelegate banbuUploadRequest:respondsDic didFinishedWithError:error];
        }
    }];
    
    [_networkQueue addOperation:request];
}
#pragma mark -  相册方法：相册文件上传 下载
- (void)modifyAlbumPicture:(NSData *)sendData par:(NSDictionary *)parDic delegate:(id)delegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_Albumfile_Byuser];    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars removeObjectForKey:@"num"];
    [pars setValue:[self getPar:BanBu_Post_Albumfile_Byuser] forKey:@"fc"];//fc
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];//loginid
    NSString *encodedStr = [sendData base64EncodedString];
    [pars setValue:encodedStr forKey:@"sfile"];//sfull
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    
    request.delegate = delegate;
    
    [request setPostValue:jsonfrom forKey:@"jsonfrom"];
    
    __block typeof(delegate)blockDelegate = delegate;
    
    [request setFailedBlock:^{
        //        if (noticeNum<3) {
        //            MyAppDataManager.banbuHostIP = BanBuHost;
        //            [MyAppDelegate getServerList];
        //            noticeNum ++;
        //        }
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            [blockDelegate banbuRequestDidFinished:nil error:request.error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            NSDictionary *respond = [NSDictionary dictionaryWithJSONData:resFrom64 error:&error];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:respond];
            
            [respondsDic setValue:[parDic valueForKey:@"num"] forKey:@"num"];
            [respondsDic setValue:[NSNumber numberWithBool:YES] forKey:@"isModify"];//返回这是修改相册数据
            [respondsDic setValue:[parDic valueForKey:@"kindof"]  forKey:@"kindof"];
            [respondsDic setValue:[parDic valueForKey:@"albumid"] forKey:@"albumid"];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    
    [_networkQueue addOperation:request];
    
}

#pragma mark - 上传视频认证数据
- (void)uploadVerifyData:(NSData *)videoData image:(NSData *)imageData delegate:(id)delegate;
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_Post_Video_Byverify];
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];

    [pars setValue:[self getPar:BanBu_Post_Video_Byverify] forKey:@"fc"];//fc
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];//loginid
    
    NSString *videoEncoder = [videoData base64EncodedString];
    [pars setValue:videoEncoder forKey:@"svideo"];//
    NSString *imageEncoder = [imageData base64EncodedString];
    [pars setValue:imageEncoder forKey:@"simage"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    
    request.delegate = delegate;
    
    [request setPostValue:jsonfrom forKey:@"jsonfrom"];
    
    __block typeof(delegate)blockDelegate = delegate;
    
    [request setFailedBlock:^{

        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            [blockDelegate banbuRequestDidFinished:nil error:request.error];
        }
        BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        //            ap.tabbarController.
        [TKLoadingView showTkloadingAddedTo:ap.tabbarController.view point:CGPointMake(160, 160) title:NSLocalizedString(@"verifyFail", nil)  activityAnimated:NO duration:3];
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:nil];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            NSDictionary *respond = [NSDictionary dictionaryWithJSONData:resFrom64 error:&error];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:respond];
            
            
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
        BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        //            ap.tabbarController.
        [TKLoadingView showTkloadingAddedTo:ap.tabbarController.view point:CGPointMake(160, 160) title:NSLocalizedString(@"verifyChecking", nil)  activityAnimated:NO duration:3];
    }];
    
    [_uploadQueue addOperation:request];
    
}

#pragma mark -
- (NSDictionary *)getAMsgFrom64String:(NSString *)encodedString
{
    NSData *decodedData = [NSData dataFromBase64String:encodedString];
    return [NSDictionary dictionaryWithJSONData:decodedData error:nil];
}

#pragma mark - 下载主题、彩蛋、收藏的图片、语音、表情等
//获取服务器上多媒体数据：图片、语音等
- (void)getEmoImage:(NSString *)mediaUrlStr withImageName:(NSString *)imageName withFolder:(NSString *)folderName delegate:(id)adelegate withImageView:(UIImageView *)imageView
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [self pathForEmo:imageName withFolder:folderName];
    
    if ([FileManager fileExistsAtPath:savePath])
    {
        return;
    }
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    
    request.delegate = adelegate;
    request.username = @"playvoice";
    
    [request setFailedBlock:^{
        
        if([adelegate respondsToSelector:@selector(removeTk)])
        {
            [adelegate removeTk];
            
        }else if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:@"n" forKey:@"ok"];
            
            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    
    [request setCompletionBlock:^{
        
        imageView.image = [UIImage imageWithContentsOfFile:savePath];
        
        if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            imageView.image = [UIImage imageWithContentsOfFile:savePath];
            
            if([[mediaUrlStr pathExtension] isEqualToString:@"amr"])
            {
                NSData *audioData = [RecordAudio decodeAMRToWav:savePath];
                [FileManager createFileAtPath:savePath contents:audioData attributes:nil];
            }
            
            if ([folderName isEqualToString:CollectionFolder])//下载的是收藏的表情
            {
                NSString * contentPath = [AppComManager pathForCollect:mediaUrlStr];
                
                [FileManager copyItemAtPath:savePath toPath:contentPath error:nil];
            }
            
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:mediaUrlStr forKey:@"oldImageUrl"];
            
            
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            
//            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    
    [_networkQueue addOperation:request];
}

//下载主题
-(void)downLoadFileWithUrl:(NSString *)url withsaveName:(NSString *)fileName delegate:(id)delegate
{
    //去空格
    url = [self trimBlankString:url];
    
    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    NSString *rootDir = NSTemporaryDirectory();
    request.delegate = delegate;
    [request setDownloadDestinationPath:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]]];
    
    [_networkQueue addOperation:request];
    __block typeof(delegate)blockDelegate = request.delegate;
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
     }];
    [request setFailedBlock:^{

        NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
        
        [ThemeManager.themeDownLoading removeObjectForKey:[[fileName substringToIndex:fileName.length-4] substringFromIndex:1]];
        if(blockDelegate&&[blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSDictionary *resDic = [NSDictionary dictionaryWithObjectsAndKeys:[fileName substringToIndex:1],@"row",[NSNumber numberWithBool:NO],@"ok",nil];
            BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;

            [TKLoadingView showTkloadingAddedTo:ap.tabbarController.view point:CGPointMake(160, 160) title:NSLocalizedString(@"network_error", nil)  activityAnimated:NO duration:1];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"downLoadThemeComplete" object:self userInfo:resDic];
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    __block NSString *path = [[NSString stringWithString:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]]] retain];
    [request setCompletionBlock:^{
        //设置解压文件夹的路径
        NSString *unZipPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        unZipPath = [unZipPath stringByAppendingPathComponent:@"themeList"];
        unZipPath = [unZipPath stringByAppendingPathComponent:[[fileName substringToIndex:fileName.length-4] substringFromIndex:1]];
        //初始化ZipArchive
        ZipArchive *zip = [[ZipArchive alloc] init];
        BOOL result;
        
        if ([zip UnzipOpenFile:path]) {
            
            result = [zip UnzipFileTo:unZipPath overWrite:YES];//解压文件
            if (!result) {
                //解压失败
            }else {
                //解压成功
            }
            [zip UnzipCloseFile];//关闭
            NSDictionary *resDic = [NSDictionary dictionaryWithObjectsAndKeys:[fileName substringToIndex:1],@"row",[NSNumber numberWithBool:YES],@"ok",nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"downLoadThemeComplete" object:self userInfo:resDic];
            [ThemeManager.themeDown setObject:[NSNumber numberWithBool:YES] forKey:[[fileName substringToIndex:fileName.length-4] substringFromIndex:1]];
            [ThemeManager.themeDownLoading removeObjectForKey:[[fileName substringToIndex:fileName.length-4] substringFromIndex:1]];
            [UserDefaults setValue:ThemeManager.themeDown forKey:@"downLoadTheme"];
            BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            //            ap.tabbarController.
            [TKLoadingView showTkloadingAddedTo:ap.tabbarController.view point:CGPointMake(160, 160) title:NSLocalizedString(@"themeDownLoadComplete", nil)  activityAnimated:NO duration:1];
        }
        [zip release];
        
    }];
}


//下载彩蛋图片、语音
-(void)downLoadEggsWithUrl:(NSString *)url withSaveName:(NSString *)fileName delegate:(id)delegate
{
    //去空格
    url = [self trimBlankString:url];
    
    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    NSString *rootDir = NSTemporaryDirectory();
    request.delegate = delegate;
    [request setDownloadDestinationPath:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]]];
    
    [_networkQueue addOperation:request];
    __block typeof(delegate)blockDelegate = request.delegate;
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
     }];
    [request setFailedBlock:^{
        
        NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
        
        if(blockDelegate&&[blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    __block NSString *path = [[NSString stringWithString:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]]] retain];
    [request setCompletionBlock:^{
        //设置解压文件夹的路径
        NSString *unZipPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        unZipPath = [[unZipPath stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:fileName];
        
        //先删除以前的彩蛋版本
        [FileManager removeItemAtPath:unZipPath error:nil];

        //初始化ZipArchive
        ZipArchive *zip = [[ZipArchive alloc] init];
        
        BOOL result = NO;
        
        if ([zip UnzipOpenFile:path])//判断能不能打开压缩文件
        {
            result = [zip UnzipFileTo:unZipPath overWrite:YES];//解压文件
            if (!result)
            {
                //解压失败
            }
            else
            {
                //解压成功
            }
            [zip UnzipCloseFile];//关闭
        }
        [zip release];
    }];
}

//下载表情包
-(void)downLoadEmoWithUrl:(NSString *)url withEmoInfoDic:(NSDictionary *)emoInfoDic delegate:(id)delegate
{
    //去空格
    url = [self trimBlankString:url];
    
    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    NSString *rootDir = NSTemporaryDirectory();
    request.delegate = delegate;
    [request setDownloadDestinationPath:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[self remove_:[emoInfoDic valueForKeyPath:Keyid]]]]];
    [request setDownloadProgressDelegate:delegate];
    
    
    [_networkQueue addOperation:request];
    __block typeof(delegate)blockDelegate = request.delegate;
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total)
     {
         
     }];
    [request setFailedBlock:^{
        
        NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
        
        if(blockDelegate&&[blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    __block NSString *path = [[NSString stringWithString:[rootDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[self remove_:[emoInfoDic valueForKeyPath:Keyid]]]]] retain];
    [request setCompletionBlock:^{
        //设置解压文件夹的路径
        NSString *unZipPath = [AppComManager pathForFolder:[self remove_:[emoInfoDic valueForKeyPath:Keyid]]];
        if ([FileManager fileExistsAtPath:unZipPath])
        {
            //先删除以前的版本
            [FileManager removeItemAtPath:unZipPath error:nil];
        }
                
        //初始化ZipArchive
        ZipArchive *zip = [[ZipArchive alloc] init];
        
        BOOL result = NO;
        
        if ([zip UnzipOpenFile:path])//判断能不能打开压缩文件
        {
            result = [zip UnzipFileTo:unZipPath overWrite:YES];//解压文件
            if (!result)
            {
                //解压失败
            }
            else
            {
                //解压成功
            }
            [zip UnzipCloseFile];//关闭
        }

        
        //将下载信息添加到下载文件中
        NSMutableDictionary * emoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
        if (emoDic == nil)
        {
            emoDic = [NSMutableDictionary dictionaryWithCapacity:5];
        }
        
        NSMutableDictionary * emoInfoDictionary = [NSMutableDictionary dictionaryWithDictionary:emoInfoDic];
        
        //设置下载状态为已下载
        [emoInfoDictionary setValue:[NSNumber numberWithBool:YES] forKey:KeyDownloadState];
        
        //设置下载时间
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [emoInfoDictionary setValue:[formatter stringFromDate:[NSDate date]] forKey:KeyDownloadTime];
        
        [emoDic setValue:emoInfoDictionary forKey:[emoInfoDic valueForKey:Keyid]];

        //设置表情索引
        [emoInfoDictionary setValue:[NSNumber numberWithInteger:emoDic.count-1] forKey:KeyIndex];
        
        //归档
        [NSKeyedArchiver archiveRootObject:emoDic toFile:DownloadInfoPath];
        
        [formatter release];
        [zip release];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KFinishDownloadingEmo object:nil];
        
        //刷新表情键盘
        [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshDownloadedEmo object:nil];
    }];
}

//下载收藏的图片、语音文件
-(void)downloadAmsgFileWithUrl:(NSString *)fileUrl withUserId:(NSString *)userid withFolder:(NSString *)folderName withDelegate:(id)delegate
{
    //去空格
    fileUrl = [self trimBlankString:fileUrl];
    
    NSString *savePath = nil;
    
    if ([folderName isEqualToString:CollectionFolder])
    {
        savePath = [self pathForCollect:fileUrl];
    }
    else
    {
        savePath = [self pathForCollectImage:fileUrl];
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    
    request.username = fileUrl;
    
    __block typeof(delegate)blockDelegate = request.delegate;
    [request setDownloadSizeIncrementedBlock:^(long long size) {
        request.totalBytesSent = request.totalBytesRead;
    }];
    
    
    [request setFailedBlock:^{
        
    }];
    
    [request setCompletionBlock:^{
        
        if([[fileUrl pathExtension] isEqualToString:@"amr"])
        {
            //2014年09月24日10:26:00把amr格式的音频数据转换成wav格式存储
            NSData *audioData = [RecordAudio decodeAMRToWav:savePath];
            if(audioData){
                [FileManager createFileAtPath:savePath contents:audioData attributes:nil];
                //
                //                RecordAudio *recod=[[[RecordAudio alloc]init] autorelease];
                //
                //                time = [recod playDuration:audioData];
                //                
            }
        }

        if ([blockDelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            NSMutableDictionary * respondsDic = [NSMutableDictionary dictionaryWithCapacity:8];
            [respondsDic setValue:[NSNumber numberWithBool:YES] forKey:@"ok"];
            
            [blockDelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
        if (userid)
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:KFinishdownloadingAmsgFile object:nil];
        }
        else
        {
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
        
    }];

    [_networkQueue addOperation:request];

}

//获取服务器上魔法文字的素材图片
- (void)getMagicWordsImage:(NSString *)mediaUrlStr withFolder:(NSString *)folderName delegate:(id)adelegate withImageView:(UIImageView *)imageView
{
    //去空格
    mediaUrlStr = [self trimBlankString:mediaUrlStr];
    
    NSString *savePath = [self pathForMagicWordsImage:mediaUrlStr];
    
    if ([FileManager fileExistsAtPath:savePath])
    {
        return;
    }
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:mediaUrlStr]];
    [request setAllowResumeForFileDownloads:NO];
    [request setDownloadDestinationPath:savePath];
    
    request.delegate = adelegate;
    request.username = @"playvoice";
    
    [request setFailedBlock:^{
        
        if([adelegate respondsToSelector:@selector(removeTk)])
        {
            [adelegate removeTk];
            
        }else if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            [ASIHTTPRequest removeFileAtPath:savePath error:nil];
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            [respondsDic setValue:@"n" forKey:@"ok"];
            
            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:request.error];
        }
    }];
    
    [request setCompletionBlock:^{
        
        imageView.image = [UIImage imageWithContentsOfFile:savePath];
        
        if([adelegate respondsToSelector:@selector(banbuDownloadRequest:didFinishedWithError:)])
        {
            imageView.image = [UIImage imageWithContentsOfFile:savePath];
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithObject:request.username forKey:@"requestname"];
            
            [respondsDic setValue:@"y" forKey:@"ok"];
            [respondsDic setValue:mediaUrlStr forKey:@"oldImageUrl"];
                                
            //            [adelegate banbuDownloadRequest:respondsDic didFinishedWithError:nil];
        }
    }];
    
    [_networkQueue addOperation:request];
}

#pragma mark -  公共方法：获取缓存路径
-(NSString *)remove_:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"_" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"_" withString:@""];
    
    return string;
}

-(NSString *)pathForFolder:(NSString *)folderName
{
    NSString * folder = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:MyAppDataManager.useruid] stringByAppendingPathComponent:@"Download"];
    if (![FileManager fileExistsAtPath:folder])
    {
        [FileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * filePath = [folder stringByAppendingPathComponent:folderName];
    
    return filePath;
}

//表情的路径
-(NSString *)pathForEmo:(NSString *)emoName withFolder:(NSString *)folderName
{
    NSString * folder = [[[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:MyAppDataManager.useruid] stringByAppendingPathComponent:@"Download"] stringByAppendingPathComponent:folderName];
    
    if (![FileManager fileExistsAtPath:folder])
    {
        [FileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * filePath = [folder stringByAppendingPathComponent:emoName];
    
    return filePath;
}

- (NSString *)pathForMagicWordsImage:(NSString *)imagePath
{
    if (imagePath == nil)
    {
        return @"";
    }
    const char *str = [imagePath UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:MyAppDataManager.useruid] stringByAppendingPathComponent:@"Download"];
    
    NSString * folder = [cachePath stringByAppendingPathComponent:MagicWordsFolder];
    
    if (![FileManager fileExistsAtPath:folder])
    {
        [FileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * filePath = [folder stringByAppendingPathComponent:filename];
    
    return filePath;
}

- (NSString *)pathForCollect:(NSString *)emoPath
{
    if (emoPath == nil)
    {
        return @"";
    }
    const char *str = [emoPath UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:MyAppDataManager.useruid] stringByAppendingPathComponent:@"Download"];
    
    NSString * folder = [cachePath stringByAppendingPathComponent:CollectionFolder];
    
    if (![FileManager fileExistsAtPath:folder])
    {
        [FileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * filePath = [folder stringByAppendingPathComponent:filename];
    
    return filePath;
}

- (NSString *)pathForCollectImage:(NSString *)imagePath
{
    if (imagePath == nil)
    {
        return @"";
    }
    const char *str = [imagePath UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:MyAppDataManager.useruid] stringByAppendingPathComponent:@"Download"];
    
    NSString * folder = [cachePath stringByAppendingPathComponent:ManuscriptFolder];
    
    if (![FileManager fileExistsAtPath:folder])
    {
        [FileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * filePath = [folder stringByAppendingPathComponent:filename];
    
    return filePath;
}

//下载音频文件路径
- (NSString *)pathForMedia:(NSString *)mediaName
{
    if (mediaName == nil)
    {
        return @"";
    }
    const char *str = [mediaName UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"];
    
    return [cachePath stringByAppendingPathComponent:filename];
}

- (NSString *)pathForMsgMedia:(NSString *)mediaName
{
    if (mediaName == nil)
    {
        return @"";
    }
    const char *str = [mediaName UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MsgImageCache"];
    
    return [cachePath stringByAppendingPathComponent:filename];
}

- (NSString *)pathForVideoMsgMedia:(NSString *)mediaName
{
    if (mediaName == nil)
    {
        return @"";
    }
    const char *str = [mediaName UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MsgImageCache"];
    
    return [cachePath stringByAppendingPathComponent:filename];
}

//获取消息路径
- (NSString *)pathForMsgMedia:(NSString *)mediaName cacheFolder:(NSString *)folderName
{
    if (mediaName == nil)
    {
        return @"";
    }
    const char *str = [mediaName UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:folderName];
    
    return [cachePath stringByAppendingPathComponent:filename];
}

//视频相册的路径
- (NSString *)pathForVideoAlbumMedia:(NSString *)mediaName
{
    if (mediaName == nil)
    {
        return @"";
    }
    const char *str = [mediaName UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"AlbumFolder"];
    
    return [cachePath stringByAppendingPathComponent:filename];
}

#pragma mark - 开启长连接，接收消息

- (void)stopReceiveMsgForUid:(NSString *)uid
{
    [_receiveMsgTimer invalidate];
    _receiveMsgTimer = nil;
    
    if(uid)
    {
        [_receiveInfo removeObjectForKey:@"fromUid"];
        [_receiveInfo removeObjectForKey:@"singleDelegate"];
    }
    else
    {
        [_receiveInfo removeObjectForKey:@"globleDelegate"];
        [_receiveInfo removeObjectForKey:@"counter"];
    }
}


- (void)startReceiveMsgFromUid:(NSString *)uid forDelegate:(id)delegate
{
    if([_receiveMsgTimer isValid])
    {
        [_receiveMsgTimer invalidate];
        _receiveMsgTimer = nil;
    }
    
    if(uid)
    {
        [_receiveInfo setValue:uid forKey:@"fromUid"];
        [_receiveInfo setValue:delegate forKey:@"singleDelegate"];
    }
    else
    {
        [_receiveInfo setValue:delegate forKey:@"globleDelegate"];
        [_receiveInfo setValue:[NSNumber numberWithInteger:0] forKey:@"counter"];
    }
    
    _receiveMsgTimer = [NSTimer scheduledTimerWithTimeInterval:SepTimeInterval
                                                        target:self
                                                      selector:@selector(receviceMsg)
                                                      userInfo:nil
                                                       repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_receiveMsgTimer forMode:NSRunLoopCommonModes];
}

- (void)receviceMsg
{
    NSInteger counter = [[_receiveInfo valueForKey:@"counter"] integerValue];
    NSString *fromUid = [_receiveInfo valueForKey:@"fromUid"];
    
    if(fromUid)
    {
        [self receiveMsgFromUser:fromUid delegate:[_receiveInfo valueForKey:@"singleDelegate"]];
        
        if([AppComManager.receiveMsgTimer isValid])
        {
            [AppComManager.receiveMsgTimer invalidate];
            
            AppComManager.receiveMsgTimer=nil;
        }
    }
    else
    {
        counter ++;
    }
    // 判断是不是Wifi  还是Wifi
    
    if((counter > GlobleSepTimeInterval/SepTimeInterval)&&!fromUid)
    {
        counter = 0;
        
        [self receiveMsgFromUser:nil delegate:[_receiveInfo valueForKey:@"globleDelegate"]];
        if([AppComManager.receiveMsgTimer isValid])
        {
            [AppComManager.receiveMsgTimer invalidate];
            
            AppComManager.receiveMsgTimer=nil;
        }
    }
    [_receiveInfo setValue:[NSNumber numberWithInteger:counter] forKey:@"counter"];
}

- (void)receiveMsgFromUser:(NSString *)userid delegate:(id)delegate     //如果userid为空，则为接收全局消息
{
    NSString *query = BanBu_ReceiveMessage_From_Server_V4;      //新改版：2013-7-8 17：40：00无论userid是否为空都访问_V3接口
    
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:1];
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    
    //加入校验字段
    NSString * key = [NSString stringWithFormat:@"%@lastFlag",MyAppDataManager.useruid];
    AppComManager.lastflag = [UserDefaults valueForKey:key];
    
    [pars setValue:AppComManager.lastflag forKey:@"lastflag"];
    
    NSString *langauage=[MyAppDataManager getLanguageSubmitToServer];
    
    [pars setValue:langauage forKey:@"lang"];
    
    NSMutableArray *boolArr;
    
    NSMutableArray *interfaceList=[[[NSMutableArray alloc]initWithCapacity:10]autorelease];
    
    if([[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"boolKey"])
    {
        boolArr=[NSMutableArray arrayWithArray:[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"boolKey"]];
    }
    else
    {
        boolArr=[NSMutableArray arrayWithObjects:@"1",@"1", nil];
    }
    
    NSDictionary * allMessage = [self getInterfaceList];
    NSDictionary * onLineInfo = [self getOnlineInfo_UidList];
//    NSDictionary * readStatus = [self getReadStatus];
    NSLog(@"test");
    [interfaceList addObject:allMessage];
    [interfaceList addObject:onLineInfo];
//    [interfaceList addObject:readStatus];
    
    if (1)
    {
        NSMutableDictionary *allMessage=[[[NSMutableDictionary alloc]initWithCapacity:10] autorelease];
        
        // 这是fc 那一层的get_friendaction_ofmy
        [allMessage setValue:[self getPar:BanBu_Get_Friend_FriendDos] forKey:@"fc"];
        
        // 这是prama 的一层
        NSMutableDictionary *subAllMessage=[[[NSMutableDictionary alloc]initWithCapacity:10]autorelease];

        NSString * timeNowString_hao = [UserDefaults valueForKey:KeyLastSeeFriendDynamicTime];
        NSString * timeNowString_mo = [UserDefaults valueForKey:KeyLastSeeMoDynamicTime];
        if (timeNowString_hao == nil || [timeNowString_hao isEqualToString:@""])
        {
            NSDate * nowDate = [NSDate date];
            
            NSDateFormatter * formatter = [[[NSDateFormatter alloc]init] autorelease];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            timeNowString_hao = [formatter stringFromDate:[nowDate dateByAddingTimeInterval:-8*60*60]];//8小时前
        }
        
        if (timeNowString_mo == nil || [timeNowString_mo isEqualToString:@""])
        {
            NSDate * nowDate = [NSDate date];
            
            NSDateFormatter * formatter = [[[NSDateFormatter alloc]init] autorelease];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            timeNowString_mo = [formatter stringFromDate:[nowDate dateByAddingTimeInterval:-8*60*60]];//8小时前
        }
        
        [subAllMessage setValue:timeNowString_hao forKey:@"fromtime_hao"];
        [subAllMessage setValue:timeNowString_mo forKey:@"fromtime_mo"];
        
        [subAllMessage setValue:@"*" forKey:@"userof"];
        
        NSString *paramaString=[[CJSONSerializer serializer]serializeDictionary:subAllMessage];
        
        paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
        
        [allMessage setValue:paramaString forKey:@"param"];
        
        [interfaceList addObject:allMessage];
    }
    
//    NSLog(@"interfaceList:%@",interfaceList);
    [pars setValue:interfaceList forKey:@"interfacelist"];
    
    if (!self.isReceivingDialods && ([[UserDefaults valueForKey: [UserDefaults valueForKey:@"myID"]] valueForKey:@"loginid"]))
    {
        //加经纬度
        int count = [[UserDefaults objectForKey:@"longLinkLocationCount"] intValue];
        if (count<0)
        {
            count=0;
        }
        if (count>2)
        {
            count = 0;
            [AppLocationManager getMyLocation];
        }
        
        //获取到经纬度信息
        [pars setValue:[NSNumber numberWithDouble:(NSInteger)(AppLocationManager.curLocation.longitude*1000000)] forKey:@"plong"];
        [pars setValue:[NSNumber numberWithDouble:(NSInteger)(AppLocationManager.curLocation.latitude*1000000)] forKey:@"plat"];
        
//        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
//        
//        jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
        
        jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
        
        requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
        
        [self receiveDataQuery:query andRequestUrlStr:requestUrlStr delegate:delegate];
        count++;
        [UserDefaults setObject:[NSNumber numberWithInt:count] forKey:@"longLinkLocationCount"];
    }
}

//发起网络请求，接收返回的数据
-(void)receiveDataQuery:(NSString *)query andRequestUrlStr:(NSString *)requestUrlStr  delegate:(id)delegate
{
    NSLog(@"开启长连接");
    [_receiveMsgQueue cancelAllOperations];
    
    self.isReceivingDialods = YES;
    requestUrlStr = [self trimBlankString:requestUrlStr];

    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = delegate;
    [request setRequestMethod:@"GET"];
    [request setShouldContinueWhenAppEntersBackground:YES];
    
    __block typeof(delegate)blockDelegate = delegate;
        
    [request setFailedBlock:^{
        
        NSLog(@"结束长连接1");
        self.isReceivingDialods = NO;
        
        self.mutableData = [NSMutableData data];
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionary];
            if([query isEqualToString:BanBu_ReceiveMessage_From_Server_V4])
            {
                [respondsDic setValue:[NSNumber numberWithInteger:ChatStatusSendFail] forKey:KeyStatus];
            }
            [respondsDic setValue:query forKey:@"fc"];
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        NSLog(@"结束长连接2");
        self.isReceivingDialods = NO;   //设置接收状态为NO，下一次可以开始接收了。
        self.mutableData  = [NSMutableData data];
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            [respondsDic setValue:query forKey:@"fc"];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                BanBu_AppDelegate * app = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                
                if (!app.logined)
                {
                    return;
                }
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                // 国际化语言包
                if([query isEqualToString:BanBu_Get_Friend_FriendDo] || [query isEqualToString:BanBu_Get_Friend_FriendDos] || [query isEqualToString:BanBu_Get_User_Neardo]|| [query isEqualToString:BanBu_Get_Broadcast] )
                {
                    if([MyAppDataManager.languageDictionary allValues].count == 0)
                    {
                        NSString *langugagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"InterNationalanguage"];
                        [MyAppDataManager.languageDictionary removeAllObjects];
                        [MyAppDataManager.languageDictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:langugagePath]]];
                    }
                    NSString *string=[[[NSString alloc]initWithData:resFrom64 encoding:NSUTF8StringEncoding] autorelease];
                    
                    string =[MyAppDataManager  IsInternationalLanguage:string];
                    
                    resFrom64=[string dataUsingEncoding:NSUTF8StringEncoding];
                    
                    [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
                    
                }
            
                
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [request setDataReceivedBlock:^(NSData * data){
        if ([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSError *error = nil;
            NSString * aCompletePackage;
            if (self.mutableData == nil)
            {
                self.mutableData = [NSMutableData data];
            }
            
            [self.mutableData appendData:data];
            data = [NSData dataWithData:self.mutableData];
            
            //utf-8解析
            NSString * string = [[[NSString alloc]initWithData:self.mutableData encoding:NSUTF8StringEncoding] autorelease];
//            NSLog(@"string:%@",string);
            
            //国际语言处理
            string = [MyAppDataManager IsInternationalLanguage:string];
            
            //去空格
            string = [self trimBlankString:string];
            
            if (string == nil || [string isEqualToString:@""])
            {
                return;
            }
            NSInteger location = [string rangeOfString:@"}"].location;
            
            if(location != NSNotFound)
            {
                //找到信息
                while (YES)
                {
                    //截取消息
                    aCompletePackage = [string substringToIndex:location];//丢弃“}}”
                    aCompletePackage = [aCompletePackage substringFromIndex:2];//丢弃前面的"{{"
                    //查看aCompletePackage是否正确 错误情况如：{{aksdabskjabds{{塑料袋咖啡}}，丢失了一部分数据
                    
                    NSInteger alocation = [aCompletePackage rangeOfString:@"{"].location;
                    //丢失后半部分的情况
                    while (alocation != NSNotFound)
                    {
                        aCompletePackage = [aCompletePackage substringFromIndex:2];
                        alocation = [aCompletePackage rangeOfString:@"{"].location;
                    }
                    
                    alocation = [aCompletePackage rangeOfString:@"}"].location;
                    //丢失前半部分的情况,说明aCompletePackage是不完整的，直接丢弃就可以
                    if (alocation != NSNotFound)
                    {
                        aCompletePackage = @"";
                        alocation = [string rangeOfString:@"}"].location;
                        self.mutableData = [NSMutableData dataWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
                        continue;
                    }
                    
                    if (location+2<string.length)
                    {
                        string = [string substringFromIndex:location+2];//截取后面的字符串
                    }
                    else
                    {
                        string = @"";
                    }
                    
                    //base64解析
                    NSData * data2 = [NSData dataFromBase64String:aCompletePackage];
                    
                    NSDictionary * respondsDic = [NSDictionary dictionaryWithJSONData:data2 error:&error];
                    
                    if ([[respondsDic valueForKey:@"resultlist"] count])//有效信息
                    {
                        
                        AppComManager.lastflag = [respondsDic valueForKey:@"lastflag"];
                        NSString * key = [NSString stringWithFormat:@"%@lastFlag",MyAppDataManager.useruid];
                        [UserDefaults setValue:AppComManager.lastflag forKey:key];
                        [UserDefaults synchronize];
                        //更新界面
                        [blockDelegate banbuRequestDidFinished:respondsDic error:error];
                    }
                    else if ([[respondsDic valueForKey:@"error"]isEqualToString:@"__loginidinvalid__"])
                    {
                        [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                        
                        break;
                    }
                    
                    //继续往后找
                    location = [string rangeOfString:@"}"].location;
                    if (location == NSNotFound)
                    {
                        self.mutableData = [NSMutableData dataWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
                        break;
                    }
                }
                return;
            }
            else//接收到的包不完整，接续接收
            {
                self.mutableData = [NSMutableData dataWithData:data];
            }
        }
    }];
    
    [_receiveMsgQueue addOperation:request];
}

//设置开启长连接的参数：屏蔽掉某些人的个人资料
-(NSDictionary *)getInterfaceList
{
    static int count = 0;
    count = 0;
    
    NSMutableDictionary *allMessage=[[[NSMutableDictionary alloc]initWithCapacity:10] autorelease];
    
    // 这是fc 那一层的
    [allMessage setValue:@"get_message_ofmy" forKey:@"fc"];
    
    // 这是prama 那一层的
    
    NSMutableDictionary *subAllMessage=[[[NSMutableDictionary alloc]initWithCapacity:10]autorelease];
    
    //设置我要屏蔽的人的ID,最近更新的人的，包括现在跟我聊天的人（这个人应该是最新的资料，因为第一次下载了该人的资料。）
    
    NSMutableString * noInfo_UIDList = [NSMutableString string];
    
    if (MyAppDataManager.chatuid)
    {
        noInfo_UIDList = [NSMutableString stringWithFormat:@"%@",MyAppDataManager.chatuid];
    }
    
    NSMutableArray * userIDArray = [MyAppDataManager getPersonalDataIn:@"60"];
    
    for (int i = 0; i< MyAppDataManager.talkPeoples.count; i++)
    {
        NSString * userID = [[MyAppDataManager.talkPeoples objectAtIndex:i]valueForKey:KeyFromUid];
        
        [userIDArray removeObject:userID];
    }
    
    for (int i = 0; i < 50 && i < userIDArray.count; i++)
    {
        //如果userid在对话列表中，就屏蔽掉，限制最多50个userID
        NSString * userID = [userIDArray objectAtIndex:i];
        if (noInfo_UIDList.length)
        {
            [noInfo_UIDList appendString:@","];
        }
        [noInfo_UIDList appendString:userID];
    }
    
    [subAllMessage setValue:noInfo_UIDList forKey:@"noinfor_uidlist"];
    
    NSString *paramaString=[[CJSONSerializer serializer]serializeDictionary:subAllMessage];
    
    paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
    
    [allMessage setValue:paramaString forKey:@"param"];
    
    return allMessage;
}

//设置开启长连接的参数：需要哪些人的在线状态
-(NSDictionary *)getOnlineInfo_UidList
{
    NSMutableDictionary * allMessage = [NSMutableDictionary dictionaryWithCapacity:2];
    
    [allMessage setValue:@"get_onlineinfor_byuidlist" forKey:@"fc"];
    
    NSMutableDictionary * onLine_uidList = [NSMutableDictionary dictionaryWithCapacity:2];
    
    //加用户在线状态:取数据库中前100条
    NSArray * userIDHidingStateArray = [MyAppDataManager getUserID:nil];
    
    NSString * getonline_uidlist = [userIDHidingStateArray componentsJoinedByString:@","];
    
    [onLine_uidList setValue:getonline_uidlist forKey:@"getonline_uidlist"];
    
    NSString * paramaString = [[CJSONSerializer serializer] serializeDictionary:onLine_uidList];
    paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
    
    [allMessage setValue:paramaString forKey:@"param"];
    
    return allMessage;
}

//设置开启长连接的参数：需要哪些人的动态
-(NSDictionary *)getFriendAction:(NSDictionary *)parmaDic
{
    NSMutableDictionary * allMessage = [NSMutableDictionary dictionaryWithCapacity:2];
    
    [allMessage setValue:@"get_friendaction_ofmy" forKey:@"fc"];
    
    NSMutableDictionary * friendaction = [NSMutableDictionary dictionaryWithCapacity:2];
    
    if (parmaDic.count)
    {
        [friendaction setValue:[parmaDic valueForKey:@"userof"] forKey:@"userof"];
    }
    else
    {
        [friendaction setValue:@"*" forKey:@"userof"];
    }
    
    //获取上次获取好友动态气泡的时间戳
    //    NSString * fromtime = [self getFriendActionFromTime];
    //
    //    [friendaction setValue:fromtime forKey:@"fromtime"];
    
    NSString * paramaString = [[CJSONSerializer serializer] serializeDictionary:friendaction];
    paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
    
    [allMessage setValue:paramaString forKey:@"param"];
    
    return allMessage;
}

//获取已读状态信息
//get_readstatus_byuidlist
-(NSDictionary *)getReadStatus
{
    static int count = 0;
    count = 0;
    //设置要获取“我”发送的信息的状态
    NSMutableString *uidlist=[[NSMutableString alloc]init];//uidlist存我给一些人发了消息，我要查看这些消息的状态
    
    //再获取一遍MyAppDataManager.talkPeoples，因为现在的MyAppDataManager.talkPeoples可能不是最新的数据了
    [MyAppDataManager readTalkList:nil WithNumber:0];
    for(int i = 0; i < 50 && i < MyAppDataManager.talkPeoples.count; i++)
    {
        NSMutableDictionary *temp = [MyAppDataManager.talkPeoples objectAtIndex:i];
        
        if([[temp valueForKey:@"me"]intValue]==1 && [[temp valueForKey:KeyStatus] intValue] !=3)
        {
            count++;
            if (count>50)
            {
                break;
            }
            if([uidlist length])
            {
                [uidlist appendString:@","];
            }
            [uidlist appendString:VALUE(@"userid", temp)];
        }
    }
    
    NSMutableDictionary *allMessage=[[[NSMutableDictionary alloc]initWithCapacity:10] autorelease];
    
    // 这是fc 那一层的
    [allMessage setValue:@"get_readstatus_byuidlist" forKey:@"fc"];
    
    // 这是prama 那一层的
    NSMutableDictionary * readed_uidlist = [NSMutableDictionary dictionaryWithCapacity:2];
    [readed_uidlist setValue:uidlist forKey:@"readed_uidlist"];
    
    NSString * paramaString = [[CJSONSerializer serializer] serializeDictionary:readed_uidlist];
    paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
    
    [allMessage setValue:paramaString forKey:@"param"];
    [uidlist release];
    
    return allMessage;
}

//去掉空格、空行
-(NSString *)trimBlankString:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    return string;
}
#pragma mark -

//上传完成
- (void)uploadFinished:(ASINetworkQueue *)queue
{
    NSMutableDictionary *resDic = [NSMutableDictionary dictionary];
    [resDic setValue:@"y" forKey:@"ok"];
    [resDic setValue:@"upload_my_photos" forKey:@"fc"];
    [resDic setValue:[queue.userInfo valueForKey:@"successNum"] forKey:@"successNum"];
    [resDic setValue:[queue.userInfo valueForKey:@"failNum"] forKey:@"failNum"];
    [resDic setValue:[queue.userInfo valueForKey:@"facelist"] forKey:@"facelist"];
    id adelegate = [queue.userInfo valueForKey:@"adelegate"];
    if([adelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        [adelegate banbuRequestDidFinished:resDic error:nil];
    queue.delegate = nil;
    [queue cancelAllOperations];
    [queue release];
}

#pragma mark - tcp
- (void)creatChatConnect
{
    static BOOL connectOK = NO;
    if(!_chatSocket)
    {
        _chatSocket = [[AsyncSocket alloc] initWithDelegate:self];
        NSError *error = nil;
        connectOK = [_chatSocket connectToHost: SERVER_IP onPort: SERVER_PORT error: &error];
        if (!connectOK)
            [_chatSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    }
    NSError *error = nil;
    if(![_chatSocket isConnected])
        [_chatSocket connectToHost:SERVER_IP onPort:SERVER_PORT error:&error];
    
}

- (void)DisconnectChat
{
    [_chatSocket disconnect];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    [_chatSocket readDataWithTimeout: -1 tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    [_chatSocket readDataWithTimeout: -1 tag: 0];
}

// 这里必须要使用流式数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *msg = [[[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"recevice:%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
    [_chatSocket readDataWithTimeout: -1 tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    self.chatSocket = nil;
}

- (BOOL)HalfHourLater:(NSString *)stime beforeTime:(NSString *)ltime
{
    if(!ltime || !stime)
        return NO;
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *currentDate = [formatter dateFromString:stime];
    if(!currentDate)
        return NO;
    NSDate *lastDate = [formatter dateFromString:ltime];
    if(!lastDate)
        return NO;
    
    return [currentDate timeIntervalSince1970]>[lastDate timeIntervalSince1970]+1800;
}


- (void)dealloc
{
    [_byUserOP release];
    [_byAllOP release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    [_networkQueue cancelAllOperations];
    [_networkQueue release];
    [_receiveMsgQueue cancelAllOperations];
    [_receiveMsgQueue release];
    
    [_chatSocket release];
    [_receiveInfo release];
    [_hostReach release];
    if(_receiveMsgTimer)
    {
        [_receiveMsgTimer invalidate];
        _receiveMsgTimer = nil;
    }
    if(_receiveSingleMsgTimer)
    {
        [_receiveSingleMsgTimer invalidate];
        
        _receiveSingleMsgTimer=nil;
    }
    [_mutableData release];
    [super dealloc];
}






- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)retain
{
    return self;
}
- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}
- (oneway void)release
{
    //do nothing
}
- (id)autorelease
{
    return self;
}

-(NSString *)creatGifDataURL:(NSString *)query par:(NSDictionary *)parDic
{
    NSString *requestUrlStr;
    
    requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    
    [pars setValue:[self getPar:query] forKey:@"fc"];
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    requestUrlStr = [AppComManager trimBlankString:requestUrlStr];
    //    NSLog (@"%@",requestUrlStr);
    return requestUrlStr;
}
#pragma mark - 上传照片
-(UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize
{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reSizeImage;
    
}
#pragma mark - 获取相册列表
- (void)getBanBuAlbumData:(NSString *)query par:(NSDictionary *)parDic delegate:(id)adelegate
{
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:parDic];
    [pars setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
    [pars setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
    [pars setValue:[self getPar:query] forKey:@"fc"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    NSLog(@"相册列表提交参数%@",pars);
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [PassWord enPassWord:jsonfrom dlegate:self];
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@ : %@",[self getPar:query],requestUrlStr);
    
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = adelegate;
    [request setRequestMethod:@"GET"];
    [request setTimeOutSeconds:10.0];
    [request setDownloadCache:[ASIDownloadCache sharedCache]];
    __block typeof(adelegate)blockDelegate = adelegate;
    
    [request setFailedBlock:^{
        
        NSLog(@"获取相册列表失败");
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:parDic];
            
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:respondsDic];
            [blockDelegate banbuRequestDidFinished:respondsDic error:error];
        }
    }];
    [request setCompletionBlock:^{
        
//        [MyAppDataManager showTime:@"加载相册完成"];
        
        NSLog(@"获取相册列表success");
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            [respondsDic setValue:[self getPar:query] forKey:@"fc"];
            
            if ([query isEqualToString:BanBu_GetMagicGid_detail])
            {
                [respondsDic setValue:[parDic valueForKey:@"title"] forKey:@"title"];
            }
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                if([respondsDic valueForKey:@"alert"])
                {
                    UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:[respondsDic valueForKey:@"alert"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                    [alert release];
                }
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    [request startAsynchronous];
}

/**
 * @函数名称：updatePhotosToAlbum:andReturnDic:
 * @函数描述：上传照片或视频
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
//上传照片的方法
-(void)updatePhotosToAlbum:(NSDictionary*)photoDict delegate:(id)adelegate
{
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithDictionary:photoDict];
    [pars removeObjectForKey:@"sfile"];
    [pars removeObjectForKey:@"sfull"];
    [pars removeObjectForKey:@"ssound"];
    [pars setValue:[self getPar:BanBu_v2_Post_Albumfile_Byuser] forKey:@"fc"];
    [pars setValue:MyAppDataManager.loginid forKey:@"loginid"];
    [pars setValue:MyAppDataManager.appVersion forKey:@"appversion"];
    [pars setValue:@"en" forKey:@"apptype"];
    [pars setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    NSLog(@"照片上传参数:%@",pars);
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:BanBu_v2_Post_Albumfile_Byuser];
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:pars];
    
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //去空格
    requestUrlStr = [self trimBlankString:requestUrlStr];
    NSLog(@"%@",requestUrlStr);
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    [request setPostValue:jsonfrom forKey:@"jsonfrom"];
    
    
    [request addData:[photoDict valueForKey:@"sfile"] withFileName:@"thumbImage" andContentType:@"image/jpg" forKey:@"sfile"];

    //视频
    if ([[photoDict valueForKey:@"kindof"] isEqualToString:@"v"])
    {
        [request addData:[photoDict valueForKey:@"sfull"] withFileName:@"fullImage" andContentType:@"video/mp4" forKey:@"sfull"];
    }
    else
    {
        [request addData:[photoDict valueForKey:@"sfull"] withFileName:@"fullImage" andContentType:@"image/jpg" forKey:@"sfull"];
    }
    //空语音不发送
    if ([[photoDict valueForKey:@"ssound"] isKindOfClass:[NSData class]])
    {
        [request addData:[photoDict valueForKey:@"ssound"] withFileName:@"ssound" andContentType:@"sound/amr" forKey:@"ssound"];
    }
    
    //    [request setPostValue:[photoDict valueForKey:@"sfile"] forKey:@"sfile"];
    //    [request setPostValue:[photoDict valueForKey:@"sfull"] forKey:@"sfull"];
    //    [request setPostValue:[photoDict valueForKey:@"ssound"] forKey:@"ssound"];
    //BanBu_ProgressController显示上传进度条
    [request setShowAccurateProgress:YES];
    [request setUploadProgressDelegate:[BanBu_ProgressController sharedManager]];
    
    [request setFailedBlock:^{
        NSLog(@"%@",request.error);
        
        //BanBu_ProgressController执行上传失败的方法
        [[BanBu_ProgressController sharedManager] falseToUpdate];
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            completeblock(nil);
        //        });
        
    }];
    
    __block NSDictionary * bphotoDict = photoDict;
    
    [request setCompletionBlock:^{
        NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
        
        NSError *error = nil;
        NSData *resFrom64 = [NSData dataFromBase64String:resStr];
        NSDictionary *respond = [NSDictionary dictionaryWithJSONData:resFrom64 error:&error];
        
        
        NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithDictionary:respond];
        
        [respondsDic setValue:[bphotoDict valueForKey:@"albumid"] forKey:@"album_id"];
        NSLog(@"%@",respondsDic);
        [[BanBu_ProgressController sharedManager] successToUpdate];
        [[NSNotificationCenter defaultCenter] postNotificationName:kSendPhotosSuccessNotification object:respondsDic];
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            completeblock(respond);
        //        });
    }];
    //    [request startSynchronous];
    [_updateAlbumdataQueue addOperation:request];
}

- (void)setProgress:(float)newProgress
{
    NSLog(@"Progress:%f",newProgress);
}

- (void)setDoubleValue:(double)newProgress
{
    NSLog(@"DoubleValue:%f",newProgress);
}

/**
 * @函数名称：asy_request
 * @函数描述：异步执行HttpRequest
 * @输入参数：(ASIFormDataRequest *)request  需要执行的request
 *          (void(^)(ASIFormDataRequest *))dataHandleBlock 请求返回后处理数据的block
 * @输出参数：N/A
 * @返回值：NSString 返回字符串
 */
+ (void)requestForm:(ASIFormDataRequest *)request dataHandleBlock:(void(^)(ASIFormDataRequest *))dataHandleBlock
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [request startSynchronous];
        dataHandleBlock(request);
    });
}
#pragma mark - 暂时停用的方法
//获取当前位置信息，开启长连接时上传位置信息
-(NSDictionary *)getMyLocation
{
    [AppLocationManager getMyLocation];
    
    //获取到经纬度信息
    NSString * locationString = [NSString stringWithFormat:@"%0.f,%0.f",AppLocationManager.curLocation.longitude*1000000,AppLocationManager.curLocation.latitude*1000000];
    
    NSMutableDictionary * allMessage = [NSMutableDictionary dictionaryWithCapacity:2];
    
    [allMessage setValue:@"get_onlineinfor_location" forKey:@"fc"];
    
    NSDictionary * locationDic = [NSDictionary dictionaryWithObjectsAndKeys:locationString,@"getonline_location", nil];
    
    NSString * paramaString = [[CJSONSerializer serializer] serializeDictionary:locationDic];
    paramaString=[[paramaString dataUsingEncoding:NSUTF8StringEncoding]base64EncodedString];
    
    [allMessage setValue:paramaString forKey:@"param"];
    
    return allMessage;
}
#pragma mark -
@end
